// 重写array中的七个方法 push pop shift unshift sort reverse
import {def} from '../utils/utils'

const arrayPrototype = Array.prototype

// 以Array.prototype为原型，创建arrayMethods对象

export const arrayMethods = Object.create(arrayPrototype)
 const methodsNeedChange = [
    'push',
    'pop',
    'shift',
    'unshift',
    'splice',
    'sort',
    'reverse'
 ]

 methodsNeedChange.forEach(methodName=>{
   const original= arrayPrototype[methodName]
   
   def(arrayMethods,methodName,function () {
    
      const ob = this.__ob__;
      let inserted = []
      switch (methodName) {
         case 'push':
         case 'unshift':   
            inserted = [...arguments]
            break;
         case 'splice':
            inserted = [...arguments].slice(2)
         default:
            break;
      }
      if(inserted){
         ob.observeArray(inserted)
      } 
      
      const result =  original.apply(this,arguments)
      ob.dep.notify()
      return result
   },false)
 })